<template>
  <div class="register-container">
    <el-card class="register-card">
      <template #header>
        <div class="card-header">
          <h2>用户注册</h2>
        </div>
      </template>
      
      <el-form 
        ref="formRef"
        :model="registerForm"
        :rules="rules"
        label-width="100px"
        class="register-form">
        
        <el-form-item label="员工ID" prop="employeeId">
          <el-input 
            v-model="registerForm.employeeId"
            placeholder="请输入员工ID">
          </el-input>
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="registerForm.username"
            placeholder="请输入用户名">
          </el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            show-password>
          </el-input>
          <el-button 
            type="primary" 
            plain 
            @click="generateRandomPassword"
            style="margin-left: 10px;">
            生成随机密码
          </el-button>
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input 
            v-model="registerForm.realName"
            placeholder="请输入真实姓名">
          </el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="registerForm.email"
            placeholder="请输入邮箱">
          </el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input 
            v-model="registerForm.phone"
            placeholder="请输入手机号">
          </el-input>
        </el-form-item>

        <el-form-item label="专业" prop="major">
          <el-input 
            v-model="registerForm.major"
            placeholder="请输入专业">
          </el-input>
        </el-form-item>

        <el-form-item label="研究方向" prop="specialization">
          <el-input 
            v-model="registerForm.specialization"
            placeholder="请输入研究方向">
          </el-input>
        </el-form-item>

        <el-form-item label="权限等级" prop="permissionLevel">
          <el-select 
            v-model="registerForm.permissionLevel"
            placeholder="请选择权限等级"
            style="width: 100%">
            <el-option label="文献上传者" :value="1" />
            <el-option label="文献标注者" :value="2" />
            <el-option label="专业老师审核" :value="3" />
            <el-option label="审核人员" :value="4" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="submitForm"
            :loading="loading">
            注册
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="text" @click="goToLogin">返回登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { ip } from '@/config/baseURL';

const router = useRouter();
const loading = ref(false);
const formRef = ref(null);

// 生成随机6位密码
const generateRandomPassword = () => {
  const randomNum = Math.floor(100000 + Math.random() * 900000);
  registerForm.password = randomNum.toString();
};

// 表单数据
const registerForm = reactive({
  employeeId: '',
  username: '',
  password: '',
  realName: '',
  email: '',
  phone: '',
  major: '',
  specialization: '',
  permissionLevel: 1,
  count: 0,
  createTime: '',
  updateTime: ''
});

// 监听手机号变化，自动更新员工ID
watch(() => registerForm.phone, (newPhone) => {
  registerForm.employeeId = newPhone;
});

// 表单验证规则
const rules = {
  employeeId: [
    { required: true, message: '请输入员工ID', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' }
  ],
  permissionLevel: [
    { required: true, message: '请选择权限等级', trigger: 'change' }
  ]
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    loading.value = true;
    
    const response = await axios.post(
      ip + '/api/b/add',
      registerForm,
      {
        headers: {
          'Content-Type': 'application/json',
          'auth': localStorage.getItem('auth')
        }
      }
    );

    if (response.data.code === 200) {
      ElMessage.success('注册成功');
      router.push('/login');
    } else {
      throw new Error(response.data.msg || '注册失败');
    }
  } catch (error) {
    console.error('注册失败:', error);
    ElMessage.error(error.message || '注册失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 返回登录页
const goToLogin = () => {
  router.push('/login');
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

.register-card {
  width: 100%;
  max-width: 600px;
  margin: auto;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.register-form {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input),
:deep(.el-input-number) {
  width: 100%;
}

.el-button {
  width: 120px;
  margin-right: 20px;
}

.el-button--text {
  width: auto;
}

@media (max-width: 768px) {
  .register-card {
    margin: 20px;
  }
  
  .register-form {
    padding: 10px;
  }
  
  :deep(.el-form-item__label) {
    float: none;
    text-align: left;
    padding: 0 0 10px;
  }
}
</style>
